package aos.client.skype;

import org.apache.log4j.Logger;

import aos.client.ClientProperties;

import com.skype.Application;
import com.skype.ApplicationAdapter;
import com.skype.Skype;
import com.skype.SkypeException;
import com.skype.Stream;


public class SkypeClient {

	static Logger logger = Logger.getLogger(SkypeClient.class);
	private Stream[] streams;

	public SkypeClient() {
		try {
			streams = connectToServer(
					ClientProperties.getInstance().getProperty(ClientProperties.APPLICATION_NAME),
					ClientProperties.getInstance().getProperty(ClientProperties.HOST)		
			);
			if((streams == null) || (streams.length == 0)){
				logger.error("Attemp to connect failed. Not connected to server.");
			} else {
			Skype.call(ClientProperties.getInstance().getProperty(ClientProperties.HOST));
			}
			
		} catch (SkypeException e) {
			logger.error("Connexion failed", e);
		}
	}

	public void writeData(String data) {
		if((streams != null) && (streams.length > 0)){
			try {
				streams[0].write(data);
			} catch (SkypeException e) {
				logger.error("Fail to write data to stream");
			}
		} else {
			logger.error("Not connected to any server.");
		}
	}


	private static Stream[] connectToServer(String applicationName, String serverName) throws SkypeException {
		Application application = Skype.addApplication(applicationName);
		application.addApplicationListener(new ApplicationAdapter() {
			@Override
			public void connected(Stream stream) throws SkypeException {
				printApplicationAndStreamName("connected:", stream);
			}

			@Override
			public void disconnected(Stream stream) throws SkypeException {
				printApplicationAndStreamName("disconnected:", stream);
			}

			private void printApplicationAndStreamName(String header, Stream stream) {
				logger.info(header + stream.getApplication().getName() + "-" + stream.getId());
			}
		});
		logger.info("Attempt to connect to " + applicationName + " on " + serverName);
		return application.connect(serverName);
	}
}
